import { createRouter, createWebHashHistory } from 'vue-router'
import { constanceRoute } from './routes'
import {setTitle} from "@/utils/utils"
import NProgress from '@/config/nprogress'
import pinia from '@/store'
import useUserStore from '@/store/modules/user'
import setting from '@/setting'
const userStore = useUserStore(pinia)

const router = createRouter({
  //路由模式
  history: createWebHashHistory(),
  routes: constanceRoute,
})

/**
 * @description 路由拦截 beforeEach
 * */
router.beforeEach(async (to, _from, next) => {
  // 动态设置标题
  const title = to.meta?.title as string
  setTitle(`${setting.title}-${title}`)
  NProgress.start()
  const token = userStore.token
  const username = userStore.username
  if (token) {
    if (to.path == '/login') {
      next({ path: '/home' })
    } else {
      if (username) {
        next()
      } else {
        try {
          await userStore.userInfo()
          next()
        } catch (error) {
          console.log(error)
          await userStore.logout()
          next({ path: '/login', query: { redirect: to.path } })
        }
      }
    }
  } else {
    if (to.path == '/login') {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})
/**
 * @description 路由跳转结束
 * */
router.afterEach(() => {
  NProgress.done()
})

/**
 * @description 路由跳转错误
 * */
router.onError((error) => {
  NProgress.done()
  console.warn('路由错误', error.message)
})

export default router
